const axios = require("axios");
const Config = require("./Config");
const {sleep} = require("./Helper");
const fs = require('fs');
const path = require('path');

class CloudSong
{
    /**
     *
     * @type {null|User}
     */
    user = null

    constructor(user)
    {
        this.user = user
    }

    /**
     *
     * @param limit 每页几条
     * @param pageIndex 页码
     * @return {Promise<array[string]>}
     */
    async getIds(pageIndex,limit = 100)
    {
        const songs = await this.getList(pageIndex,limit)
        const songIds = songs.map(song => song.songId);
        console.log('获取到的歌曲 ID 列表:', songIds);
        return songIds;
    }


    /**
     *
     * @param limit 每页几条
     * @param pageIndex 页码
     * @return {Promise<any|*[{songName,songId,fileName,matchType,album}]>}
     */
    async getList(pageIndex,limit = 100)
    {
        const apiUrl = `https://music.163.com/api/v1/cloud/get?limit=${limit}&offset=${(pageIndex - 1) * limit}`;

        try {
            const response = await axios.get(apiUrl, {
                headers: {
                    'Cookie': `${Config.cookieName}=${this.user.getCookie()}`,
                    'User-Agent': Config.userAgent,
                },
            });

            const data = response.data;

            // 检查返回数据是否合法
            if (data && data.code === 200 && data.count > 0) {
                //songName  songId fileName
                const songs = data.data; // 直接是数组
                return songs;
            } else {
                console.log('没有歌曲或接口返回异常', data);
                return [];
            }
        }catch (err) {
            console.error('请求失败:', err);
            return [];
        }
    } //end getCloudSongs();

    async changId(userId,songId,adjustSongId)
    {
        let apiUrl = "https://music.163.com/api/cloud/user/song/match?userId=" + userId + "&songId=" + songId + "&adjustSongId=" + adjustSongId;

        const response = await axios.get(apiUrl, {
            headers: {
                'User-Agent': Config.userAgent,
                'Cookie': `${Config.cookieName}=${this.user.getCookie()}` // 如果需要cookie
            }
        });
        const data = response.data;


        if (data && data.code === 200)
        {
            console.log("✅ 匹配纠正成功！名字:"+data.matchData.simpleSong.name);

            // 如果有回调逻辑可以放在这里
            // button2_Click(sender, null); 相当于调用某个函数
        } else {
            console.log("❌ 匹配纠正失败:", data);
        }
        return data;
    }


    async changeIds()
    {
        const userInfo = await this.user.getProfile();
        let page = 1;
        while (true)
        {
            const songs = await this.getList(page,100);
            page++;
            if (songs.length <= 0) break;
            for (const song of songs)
            {
                const songId = song.songId.toString();
                const songName = song.songName.toString();
                if (!(/^\d+$/.test(songName)) || songId === songName) continue;

                if (song.matchType === 'matchType')
                {
                    console.log(`${songId} ${song.songName} 状态为 matchType 跳过`);
                    continue;
                }
                console.log(`songid：${songId},songName:${songName}`);
                let apiUrl = "https://music.163.com/api/cloud/user/song/match?userId=" + userInfo.user_id + "&songId=" + songId + "&adjustSongId=" + songName;

                await this.changId(userInfo.user_id,songId,songName)
                await sleep(3000);

            }

        }

    } //end changeIds


    async saveIdsToFile()
    {
        const userInfo = await this.user.getProfile();
        // 创建下载目录
        const downloadPath = path.resolve(Config.cloudSongIdsDir,userInfo.user_id.toString());
        console.log('删除目录,'+downloadPath)
        if (fs.existsSync(downloadPath)) {
            fs.rmSync(downloadPath, { recursive: true, force: true });
        }
        console.log('创建目录,'+downloadPath)
        fs.mkdirSync(downloadPath, { recursive: true });
        let page = 1;
        while (true)
        {
            const songs = await this.getList(page,100);
            if (songs.length <= 0) break;

            for (const song of songs)
            {
                const songId = song.songId
                const filePath = path.resolve(downloadPath, `${songId}.txt`);
                if (!fs.existsSync(filePath)) {
                    fs.writeFileSync(filePath, JSON.stringify(song, null, 2)); // 创建空文件
                }
            }
            console.log('目录,'+downloadPath+`,写入第${page}页,${songs.length}`)
            page++;
        }
    }


    async changOneSongIdByName(songName,newSongId)
    {
        const userId = (await this.user.getProfile())?.user_id;
        if (!userId || userId === '') {
            console.log('请登录');
            return false;
        }
        let page = 1;
        while (true)
        {
            const songs = await this.getList(page, 100);
            page++;
            if (songs.length <= 0) break;
            for (const song of songs)
            {
                const songId = song.songId;
                if (song.songName !== songName)
                {
                    console.log(`${song.songName} 不是 ${songName} 跳过`);
                    continue;
                }
                if (song.matchType === 'matchType')
                {
                    console.log(`${songId} ${song.songName} 状态为 matchType 跳过`);
                    continue;
                }
                const data = await this.changId(userId,songId,newSongId.toString());
                console.log(`尝试将 ${songName} 匹配为 ${newSongId}`);
                if (data && data.code === 200)
                {
                    return true;
                }
                return false;
            } //end for songs
            await sleep(2000);
        }//end while
    } //end changOneSongIdByName


    async changeSongIdByName(data = {})
    {
        const userId = (await this.user.getProfile())?.user_id;
        if (!userId || userId === '') {
            console.log('请登录');
            return false;
        }
        let page = 1;
        while (true)
        {
            const songs = await this.getList(page, 100);
            page++;
            if (songs.length <= 0) break;
            for (const song of songs)
            {
                const songId = song.songId;
                const songName = song.songName
                if (song.matchType === 'matchType')
                {
                    console.log(`${songId} ${songName} 状态为 matchType 跳过`);
                    continue;
                }
                let albums = data.songMap[songName];
                if (albums === undefined) {
                    console.log(`${songId} ${songName} 专辑没有 跳过`);
                    continue;
                }

                for (const album of albums)
                {
                    const data = await this.changId(userId,songId,album.songId.toString());
                    console.log(`尝试将 ${songName} 匹配为 ${album.songId}`);
                    await sleep(2000);
                    if (data && data.code === 200)
                    {
                        break;
                    }
                } //for albums
                await sleep(2000);
            } //end for songs
        }//end while
    } //end changeSongIdByName()

}

module.exports = CloudSong